package com.shexianyu.notes.web.controller;

import com.shexianyu.notes.common.utils.MD5Util;
import com.shexianyu.notes.common.utils.ObjectUtil;
import com.shexianyu.notes.common.utils.Result;
import com.shexianyu.notes.common.utils.TokenUtil;
import com.shexianyu.notes.web.dto.LoginDTO;
import com.shexianyu.notes.web.dto.RegisterDTO;
import com.shexianyu.notes.web.entity.SysUser;
import com.shexianyu.notes.web.service.SysUserService;
import com.shexianyu.notes.web.vo.TokenVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author sxy
 * @version 1.0
 * @date 2021/2/26 14:28
 */
@Api(value = "系统用户controller", tags = "系统用户controller")
@RestController("/user")
public class SysUserController {

    private final SysUserService sysUserService;

    public SysUserController(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }


    /**
     * 登录
     *
     * @param loginDTO
     * @param bindingResult
     * @return
     */
    @ApiOperation(value = "系统用户登录")
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDTO loginDTO,
                        BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.build(400, bindingResult.getFieldError().getDefaultMessage());
        }
        String account = loginDTO.getAccount();
        String password = loginDTO.getPassword();
        String encryptPassword = MD5Util.encrypt(password);
        //获取用户信息
        SysUser user = sysUserService.findByAccount(account);
        //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(encryptPassword)) {
            return Result.build(400, "用户名或密码错误");
        } else {
            //生成token，保存到数据库
            String token = sysUserService.createToken(user);
            TokenVO tokenVO = new TokenVO();
            tokenVO.setToken(token);
            return Result.ok(tokenVO);
        }
    }

    /**
     * 退出
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "系统用户退出")
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        //从request中取出token
        String token = TokenUtil.getRequestToken(request);
        sysUserService.logout(token);
        return Result.ok();
    }

    /**
     * 用户注册
     *
     * @param registerDTO
     * @param bindingResult
     * @return
     */
    @ApiOperation(value = "系统用户注册")
    @PostMapping("/register")
    public Result register(@Validated @RequestBody RegisterDTO registerDTO,
                           BindingResult bindingResult) {
        //验证信息是否满足条件
        if (bindingResult.hasErrors()) {
            return Result.build(400, bindingResult.getFieldError().getDefaultMessage());
        }
        String account = registerDTO.getAccount();
        String username = registerDTO.getUsername();
        String password = registerDTO.getPassword();
        String repeatPassword = registerDTO.getRepeatPassword();
        //密码加密
        String encryptPassword = MD5Util.encrypt(password);
        SysUser user = sysUserService.findByAccount(account);
        if (!ObjectUtil.isEmpty(user)) {
            return Result.build(400, "该用户已存在");
        }
        if (!password.equals(repeatPassword)) {
            return Result.build(400, "两次密码不一致");
        } else {
            SysUser sysUser = new SysUser();
            sysUser.setUsername(username);
            sysUser.setAccount(account);
            sysUser.setPassword(encryptPassword);
            try {
                sysUserService.createSysUse(sysUser);
                return Result.ok("注册成功");
            } catch (Exception e) {
                e.printStackTrace();
                return Result.build(500, "服务器内部错误");
            }
        }
    }

}
